<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="#">
        <div>
            <label for="username">用户名：</label>
            <input id="username" type="text">
            <span id="usernameInfo"></span>
        </div>
        <div>
            <label for="pwd">密码</label>
            <input id="pwd" type="password">
            <span id="pwdInfo"></span>
        </div>
        <div>
            <input type="submit">
        </div>
    </form>
    <script>
        let username = document.getElementById("username");
        let usernameInfo = document.getElementById("usernameInfo");
        let pwd = document.getElementById("pwd");
        let pwdInfo = document.getElementById("pwdInfo");
        let validateUsername = function(){
            if(/^\w{6,20}$/.test(username.value)){
                usernameInfo.innerHTML = "√";
                return true;
            }else{
                usernameInfo.innerHTML = "X";
                return false;
            }
        }
        let validatePwd = function(){
            if(/^.{6,20}$/.test(pwd.value)){
                pwdInfo.innerHTML = "√";
                return true;
            }else{
                pwdInfo.innerHTML = "X";
                return false;
            }
        }
        username.onblur = validateUsername;
        pwd.onblur = validatePwd;
        document.forms[0].onsubmit = function(e){
           if(validateUsername() && validatePwd()){
                alert('成功');
           }else{
                e.preventDefault();
           }
        }
    </script>
</body>
</html>